<template>
  <div class="login-container">

    <input
      class="camera"
      ref="file1"
      type="file"
      capture="camcorder"
      accept="video/*"
      multiple
      @change="onFileChange(1,$event)"
      hidden
    >
    <input
      class="cameraInput"
      ref="file3"
      type="file"
      accept="video/*"
      @change="onFileChange(3,$event)"
      hidden
    >
    <input
      class="cameraInput"
      ref="choose_poster"
      type="file"
      accept="image/*"
      @change="onChoosePoster"
      hidden
    >
    <van-nav-bar title="拍视频"> </van-nav-bar>
    <div class="content_wrap">
      <div class="introduce_wrap">
        <textarea
          v-model="video.introduce"
          name=""
          id=""
          cols=""
          rows=""
          placeholder="写标题并使用合适的话题，能让更多人看到"
        >
        </textarea>
        <div class="topic">
          <div
            class="text"
            @click="onVideoLabelShow"
          ># 添加标签</div>
        </div>
      </div>
      <div
        class="poster"
        @click="ClickChoosePoster"
      >
        <div class="choose_poster">选封面</div>
        <img
          src="https://img0.baidu.com/it/u=2469377738,1327999834&fm=26&fmt=auto&gp=0.jpg"
          alt=""
          ref="image"
        >
      </div>
    </div>
    <div class="topic_row">
      <div
        class="topic_example"
        v-for="(item,index) in video.choosenVideoLabel"
        :key="index"
      >#{{item}}</div>

    </div>
    <van-divider />
    <van-cell
      icon="video-o"
      title="拍摄视频"
      is-link
      value=""
      @click="shootVideoAgain"
    />

    <van-cell
      icon="envelop-o"
      title="点击上传"
      is-link
      value=""
      @click="Upload"
    />
    <van-cell
      icon="location-o"
      title='定位'
      is-link
      :value="video.position"
      @click="onPopupShow"
    />
    <div class="public">
      <div
        class="text"
        @click="onUploadConfirm"
      >
        发布
      </div>
    </div>
    <van-popup
      v-model="isVideoLabelShow"
      style="height:40%;width: 80%;"
    >
      <van-tag
        size="large"
        plain
        type="primary"
        v-for="(item,index) in videoLabel"
        :key="index"
        @click="chooseLabel(item.label)"
      >{{item.label}}</van-tag>
      <van-divider>已选中</van-divider>
      <van-tag
        size="large"
        plain
        type="primary"
        v-for="(item,index) in video.choosenVideoLabel"
        :key="index"
        closeable
        @close="video.choosenVideoLabel.splice(index, 1)"
      > {{item}} </van-tag>
      <div
        class="finishLabelChoose"
        @click="isVideoLabelShow=false"
      >完成</div>
    </van-popup>
    <van-popup
      v-model="isMapShow"
      style="height: 100%;"
      class="intro-popup"
      position="bottom"
      get-container="body"
    >
      <van-nav-bar
        title="选择定位"
        left-text="返回"
        right-text="完成"
        left-arrow
        @click-left="onClickLeft"
        @click-right="isMapShow =false"
      />
      <div
        id="allmap"
        ref="allmap"
        class="allmap"
      ></div>
    </van-popup>

  </div>
</template>

<script>
import { addUserVideo } from '@/api/user'
import { getVideoLabel } from '@/api/video'

import globalBus from '@/utils/global-bus'
import BMap from 'BMap'

export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data () {
    return {
      video: {
        position: '',
        choosenVideoLabel: [],
        introduce: '',
        poster: '',
        userid: ''
      },
      currentFile: Number,
      isShootVideoShow: false,
      isMapShow: false,
      isLoaded: false,
      isVideoLabelShow: false,
      videoLabel: [],
      file: {}
    }
  },
  computed: {
    file1 () {
      return this.$refs.file1
    },
    file3 () {
      return this.$refs.file3
    }
  },
  watch: {},
  created () {
    this.video.userid = this.$store.state.user.userid
  },
  mounted () { },
  activated () {
    this.isShootVideoShow = true
    this.$refs.file1.click()
    this.video.userid = this.$store.state.user.userid

    // this.getCamera()
  },
  deactivated () {
    this.isShootVideoShow = false
  },
  methods: {
    onFileChange (index, event) {
      if (event.target.files.length) {
        this.currentFile = index
        const fileUrl = URL.createObjectURL(this[`file${index}`].files[0])
        var videoElement = document.createElement('VIDEO')
        videoElement.src = fileUrl
        videoElement.autoplay = true
        videoElement.muted = true
        videoElement.addEventListener('loadeddata', _event => {
          var canvas = document.createElement('canvas')
          canvas.width = videoElement.videoWidth * 0.8
          canvas.height = videoElement.videoHeight * 0.8
          canvas.getContext('2d').drawImage(videoElement, 0, 0, canvas.width, canvas.height)
          const poster = canvas.toDataURL('image/png')
          this.$refs.image.src = poster
          this.video.poster = poster
        })
        if (/image\/\w+/.test(this[`file${index}`].files[0].type)) {
          this.$refs.image.src = fileUrl
          return false
        }
        this.file = this[`file${this.currentFile}`].files[0]
      }
    },
    async onUploadConfirm () {
      this.$toast.loading({
        duration: 0, // 持续时间，0表示持续展示不停止
        forbidClick: true, // 是否禁止背景点击
        message: '保存中...' // 提示消息
      })

      try {
        // 构造包含文件的表单数据对象
        const formData = new FormData()
        formData.append('file', this.file)
        // formData.append('poster', this.poster)
        // 请求更新
        if (/data:image/.test(this.video.poster)) {
          var blob = this.dataURLtoBlob(this.video.poster)
        } else {
          blob = this.video.poster
        }
        formData.append('file', blob)
        formData.append('introduce', this.video.introduce)
        formData.append('choosenVideoLabel', this.video.choosenVideoLabel)
        formData.append('position', this.video.position)

        await addUserVideo(this.video.userid, formData)
        // 更新视图
        // 关闭图片预览
        this.$toast.success('保存成功')

        globalBus.$emit('user-update')
      } catch (err) {
        this.$toast.success('保存失败')
        this.$store.commit('setUser', null)
        return this.$router.push('/login')
      }
    },
    // 图片 base64 url 转 blob
    dataURLtoBlob (dataurl) {
      var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },

    shootVideoAgain () {
      this.$refs.file1.click()
    },
    shootPhotoAgain () {
      this.$refs.file2.click()
    },
    Upload () {
      this.$refs.file3.click()
    },
    onPopupShow () {
      this.isMapShow = true
      if (this.isLoaded === false) {
        this.getLocation()
      }
      this.isLoaded = true
    },
    getLocation () {
      const position = new BMap.Geolocation()
      position.enableSDKLocation()
      position.getCurrentPosition(pos => {
        this.video.position = pos.address.province + pos.address.city + pos.address.district
        this.initMap(pos)
      })
    },
    initMap (pos) {
      var that = this
      const map = new BMap.Map('allmap')
      const point = new BMap.Point(pos.point.lng, pos.point.lat)
      map.centerAndZoom(point, 15)
      map.setCurrentCity(pos.address.city)
      // 设置定位按钮位置
      var opts = { anchor: 'BMAP_ANCHOR_BOTTOM_RIGHT' }
      // 将定位控件添加到地图上
      map.addControl(new BMap.GeolocationControl(opts))
      // 设置缩放按钮位置及类型
      var ove = { anchor: 'BMAP_ANCHOR_TOP_RIGHT', type: 'BMAP_NAVIGATION_CONTROL_ZOOM' }
      // 添加缩放按钮
      map.addControl(new BMap.NavigationControl(ove))
      map.enableScrollWheelZoom(true)
      var marker = new BMap.Marker(point) // 创建标注
      map.addOverlay(marker)
      var geoc = new BMap.Geocoder({ extensions_town: true })
      map.addEventListener('click', function (e) {
        var pt = e.point
        map.clearOverlays()

        var marker2 = new BMap.Marker(pt) // 创建标注
        map.addOverlay(marker2) // 将标注添加到地图中
        geoc.getLocation(pt, function (rs) {
          var addComp = rs.addressComponents
          that.video.position = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber
        })
      })
    },
    onClickLeft () {
      this.isMapShow = false
    },
    ClickChoosePoster () {
      this.$refs.choose_poster.click()
    },
    onChoosePoster () {
      const fileUrl = URL.createObjectURL(this.$refs.choose_poster.files[0])
      this.$refs.image.src = fileUrl
      this.video.poster = this.$refs.choose_poster.files[0]
      // this.poster.
    },
    async onVideoLabelShow () {
      this.isVideoLabelShow = true
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true
      })
      const res = await getVideoLabel()
      this.videoLabel = res.data.data
      this.$toast.loading({
        message: '请选择',
        forbidClick: true,
        duration: 3
      })
    },
    chooseLabel (label) {
      var isChoosen = this.video.choosenVideoLabel.find(v => v === label)
      if (isChoosen) {
        this.$toast.loading({
          message: '已选择',
          forbidClick: true,
          duration: 2
        })
        return 1
      }
      this.video.choosenVideoLabel.push(label)
    }
  }
}

</script>

<style scoped lang="less">
.login-container {
  font-size: 15px;
  .content_wrap {
    display: flex;
    height: 150px;
    flex-wrap: wrap;

    .introduce_wrap {
      flex: 3;
      textarea {
        width: 100%;
        height: 70%;
        border: 0;
        box-sizing: border-box;
        padding: 10px;
      }

      .topic {
        margin-top: 5px;
        .text {
          float: left;
          background-color: #383641;
          color: #efffff;
          padding: 5px;
          margin-left: 5px;
        }
      }
    }

    .poster {
      width: 100%;
      height: 144px;
      flex: 1;
      position: relative;
      .choose_poster {
        content: "选封面";
        position: absolute;
        box-sizing: border-box;
        bottom: 0px;
        left: 0;
        color: #fff;
        background-color: #000;
        opacity: 0.5;
        width: 100%;
        text-align: center;
        padding-bottom: 0;
        margin-right: 10px;
        z-index: 999;
        overflow: hidden;
      }
      img {
        position: relative;
        z-index: -999;
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        margin: 10px;
        margin: 0px;
        object-fit: fill;
      }
    }
  }
  .topic_row::after {
    content: ""; /*设置内容为空*/
    height: 0; /*高度为0*/
    line-height: 0; /*行高为0*/
    display: block; /*将文本转为块级元素*/
    visibility: hidden; /*将元素隐藏*/
    clear: both;
  }
  .topic_row {
    .topic_example {
      float: left;
      color: #878793;
      padding: 5px;
      padding-bottom: 0;
      margin-left: 5px;
      float: left;
    }
  }
}

#allmap {
  width: 100%;
  height: 90%;
}
.public {
  position: fixed;
  background: #ff2c59;
  width: 80%;
  height: 50px;
  bottom: 60px;
  left: 50%;
  transform: translate(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    font-size: 30px;
  }
}
.finishLabelChoose {
  background: #ff2c59;
  text-align: center;
  line-height: 30px;
  width: 60px;
  height: 30px;
  margin: 0 auto;
  margin-top: 20px;
}
</style>
